<?php


/** 
 * 礼包管理
 * @author Legend. <xcx_legender@qq.com>
 * @param 
 * @return 
 */

namespace Admin\Controller;

class GiftController extends BaseManageController {

	protected $modelName = 'Common/gift';	

	protected $is_del	= false;

	protected $text_map = array(
		'status' => array( 0 => '禁用', '1' => '开启', '-1' => '删除'),
		'type' => ['exchange' => '兑换' , 'gamble' => '抽奖']
	);

		public function _before_index()
		{
			$map = array();//筛选条件
	        $map['status'] = array('egt',0);

			$search = trim(I('get.name', '', 'strip_tags'));
	        if($search){
	            $map['name']    =   array('like', (string)$search);
	        }

	        $this->where = $map;
		}

	protected function _initialize()
	{
		parent::_initialize();
		$game_options = event('game')->getOptions();
		$this->text_map['game_id'] = $game_options;
		$this->assign('options', ['game' => $game_options]);
		if (I('id'))
		{
			event('Gift')->flush_stock(I('id'));
		}
	}

	/** 
	 * [导入商品码]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param 
	 * @return 
	 */
	public function import($id, $codes = '')
	{

		if (IS_POST){
			if (!$codes)
			{
				return $this->error('导入的激活码为空');
			}

			$codes = explode("\r\n", $codes);
			$model = service('Codes');
			$data = [
				'object_type' => 'gift',
				'object_id'   => (int)$id,
			];
			foreach ($codes as $key) {
				$data['key'] = $key;
				$save = $model->create($data);
				$save && $model->add($save);
			}
			event('Gift')->flush_stock($id, true);
			return $this->success('操作成功');
		}
		else
		{
			$this->display();
		}
	}

	public function used($id)
	{
		$id = (int)$id;
		$map['id'] = $id;
		$model = service('Codes');
		$gift = $this->model->where($map)->find();
		$this->assign('gift', $gift);
		$where = ['object_id' => $id, 'object_type' => 'gift'];
		$lists = $this->lists($model, $where, 'status desc',[], ['key', 'status', 'uid', 'bindtime']);
		$this->_list = $lists;
		$this->display();
	}


}